﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;

namespace GameNesSL.Views
{
    using System.Threading;

    public partial class Loading : Page
    {
        public Loading()
        {
            InitializeComponent();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            GameContext.stats.TimeStartPageEnd = GameContext.stats.TimeLoadingStart = DateTime.UtcNow;
            //Start load
            StartLoad();
        }

        private void StartLoad()
        {
            //Load load load
            LoadAsync();
        }

        private void LoadAsync()
        {
            if (Cache.GameCache.HasRom(GameContext.webMethods.GameID))
            {
                GameContext.RomData = Cache.GameCache.ReadCacheRom(GameContext.webMethods.GameID);
                if (Cache.GameCache.HasSave(GameContext.webMethods.GameID))
                {
                    GameContext.SaveData = Cache.GameCache.Load(GameContext.webMethods.GameID);
                }
                LoadCompleted();
            }
            else
            {
                //loader!!
                try
                {
                    downloader.StreamAvailible += downloader_StreamAvailible;
                    downloader.Download(new Uri(string.Format("http://gamenes.net/gamebin.aspx?g={0}", GameContext.webMethods.GameID)));
                }
                catch (Exception)
                {
                    LoadError();
                }
                //GameContext.webMethods.Client.LoadGameCompleted += new EventHandler<GameNesSL.WebRef.LoadGameCompletedEventArgs>(Client_LoadGameCompleted);
                //GameContext.webMethods.Client.LoadGameAsync(GameContext.webMethods.GameID);
            }
        }

        void downloader_StreamAvailible(System.IO.Stream stream)
        {
            //Unpack!!!
            try
            {
                GameContext.RomData = Cache.Cache.Unpack(stream);
                if (GameContext.RomData.Length > 0)
                {
                    if (GameContext.ShouldLoadState)
                    {
                        GameContext.webMethods.Client.LoadGameSaveCompleted +=
                            new EventHandler<GameNesSL.WebRef.LoadGameSaveCompletedEventArgs>(
                                Client_LoadGameSaveCompleted);
                        GameContext.webMethods.Client.LoadGameSaveAsync(GameContext.webMethods.UserID,
                                                                        GameContext.webMethods.GameID);
                    }
                    else
                    {
                        LoadCompleted();
                    }
                }
                else
                {
                    LoadError();
                }
            }
            catch (Exception)
            {
                LoadError();
            }
        }

        void Client_LoadGameCompleted(object sender, GameNesSL.WebRef.LoadGameCompletedEventArgs e)
        {
            try
            {
                GameContext.RomData = Convert.FromBase64String(e.Result);
                if (GameContext.RomData.Length > 0)
                {
                    if (GameContext.ShouldLoadState)
                    {
                        GameContext.webMethods.Client.LoadGameSaveCompleted +=
                            new EventHandler<GameNesSL.WebRef.LoadGameSaveCompletedEventArgs>(
                                Client_LoadGameSaveCompleted);
                        GameContext.webMethods.Client.LoadGameSaveAsync(GameContext.webMethods.UserID,
                                                                        GameContext.webMethods.GameID);
                    }
                    else
                    {
                        LoadCompleted();
                    }
                }
                else
                {
                    LoadError();
                }
            }
            catch (Exception)
            {
                LoadError();
            }
        }

        void Client_LoadGameSaveCompleted(object sender, GameNesSL.WebRef.LoadGameSaveCompletedEventArgs e)
        {
            try
            {
                GameContext.SaveData = Convert.FromBase64String(e.Result);
            }
            catch (Exception)
            {
                
            }
            finally
            {
                LoadCompleted();
            }
        }

        private void LoadCompleted()
        {
            GameContext.stats.StartsPlaying = true;
            NavigationService.Navigate(new Uri("/GamePage", UriKind.Relative));
            
        }
        private void LoadError()
        {
            GameContext.stats.GotLoadErrors++;
            GameContext.ErrorDescription = "Error loading rom from site";
            NavigationService.Navigate(new Uri("/Error", UriKind.Relative));
        }

        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            GameContext.stats.TimeLoadingEnd = DateTime.UtcNow;
        }
    }
}
